<?php
/**
 * Created by PhpStorm.
 * User: HeiYanHeiMao
 * Date: 2020/2/25
 * Time: 12:19
 */

namespace app\model;


use GuzzleHttp\Client;
use think\facade\Db;
use think\facade\Cache;
require_once '../sdk/API-PHP/API_PHP_DEMO.php';
class StoreModel
{
    private static $baseTable = 'eb_store'; // 商户表
    private static $schoolTable = 'eb_school'; // 学校表
    private static $scopeTable = 'eb_scope'; // 经营范围表
    private static $middleTable = 'eb_school_store'; // 学校 商户中间表
    private static $orderTable = 'eb_order'; // 订单表

    /**商户注册
     * @param $input
     * @return \think\response\Json
     */
    public static function register($input)
    {
        $flag = false;
        try {
            // 判断学校是否存在
            $schoolCount = Db::table(self::$schoolTable)->where('id', 'in', $input['school_ids'])->count();
            $schoolIds = explode(',', $input['school_ids']);
            if ($schoolCount != count($schoolIds)) return jsonFail('存在未知学校，注册失败');
            // 判断经营范围是否存在
            $scopeCount = Db::table(self::$scopeTable)->where('id', 'in', $input['scope_ids'])->count();
            if ($scopeCount != count(explode(',', $input['scope_ids']))) return jsonFail('存在未知经营范围，注册失败');
            // 判断账号是否已经注册
            $storeInfo = Db::table(self::$baseTable)->field('id')->where('bank_phone', $input['bank_phone'])->find();
            if ($storeInfo) return jsonFail('该账号已经被注册');
            // 判断账号是否已经注册
            $shop_name = Db::table(self::$baseTable)->field('id')->where('shop_name', $input['shop_name'])->find();
            if ($shop_name) return jsonFail('店铺名称不能重复');
            // 获取经纬度
            $client = new Client();
            $response = $client->request('GET', 'https://apis.map.qq.com/ws/geocoder/v1/', [
                'query' => [
                    'address' => $input['address'],
                    'key' => config('tools.map.key')
                ]
            ]);
            $content = json_decode($response->getBody()->getContents(), true);
            if ($content['status'] != 0) return jsonFail('地址' . $content['message']);
            $input['longitude'] = $content['result']['location']['lng'];
            $input['latitude'] = $content['result']['location']['lat'];
            $input['pwd'] = sha1($input['pwd']);
            $input['create_time'] = time();
            unset($input['repwd']);
            unset($input['school_ids']);
            // 添加数据
            Db::startTrans();
            $flag = true;
            $storeId = Db::table(self::$baseTable)->insertGetId($input);
            $data = [];
            foreach ($schoolIds as $schoolId) {
                array_push($data, [
                    'school_id' => $schoolId,
                    'store_id' => $storeId
                ]);
            }
            $count = Db::table(self::$middleTable)->insertAll($data);
            if ($storeId >= 1 && $count == count($schoolIds)) {
                $data = [
                    'id'=>$storeId,
                    'time_interval'=>$input['time_interval'],//营业时间
                    'send_range'=>$input['send_range'],//配送时间
                    'shop_name'=>$input['shop_name'],
                    'bank_phone'=>$input['bank_phone'],
                    'is_special'=>1,
                    'proportion'=>10,
                ];
                $addRtn = Cache::store('redis')->handler()->hMset('dxsd-store-' .$storeId,$data);
                if ($addRtn===true){
                    Db::commit();
                    return jsonSuccess('商户注册成功');
                } else {
                    Db::rollback();
                    return jsonFail('系统错误~');
                }
            }else{
                Db::rollback();
                return jsonFail('商户注册失败');
            }
        } catch (\Exception $e) {
            if ($flag == true) Db::rollback();
            return jsonFail($e->getMessage());
        }
    }
    /**商户更新
     * @param $input
     * @return \think\response\Json
     */
    public static function edit($input,$storeId)
    {
        $flag = false;
        try {
            // 判断经营范围是否存在
            $scopeCount = Db::table(self::$scopeTable)->where('id', 'in', $input['scope_ids'])->count();
            if ($scopeCount != count(explode(',', $input['scope_ids']))) return jsonFail('存在未知经营范围，注册失败');
            // 添加数据
            Db::startTrans();
            $flag = true;
            $storeId = Db::table(self::$baseTable)->where('id',$storeId)->update($input);
            if ($storeId!=0) {
//                $data = [
//                    'id'=>$storeId,
//                    'send_start'=>$input['send_start'],
//                    'send_end'=>$input['send_end'],
//                    'shop_name'=>$input['shop_name'],
//                    'bank_phone'=>$input['bank_phone'],
//                ];
//                $editRtn = Cache::store('redis')->handler()->hMSet('dxsd-store-' . $storeId, $data);
//                if ($editRtn === true) {
                    Db::commit();
                    return jsonSuccess('编辑成功！');
                } else {
                    Db::rollback();
                    return jsonFail('编辑失败！');
                }
        } catch (\Exception $e) {
            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }
    /**商户登录
     * @param $input
     * @return \think\response\Json
     */
    public static function login($input)
    {
        try {
            // 获取商户信息-
            $info = Db::table(self::$baseTable)->field('id,pwd')->where('bank_phone', $input['phone'])->find();
            if ($info == null) return jsonFail('该商户不存在');
            if (sha1($input['pwd']) != $info['pwd']) return jsonFail('密码错误');
            $token = md5('token+store'.time().'-'.$info['id']);
            $expire = 12*60*60;
            if (Cache::store('redis')->handler()->set($token,$info['id'], $expire) === true) {
                return jsonSuccess('登录成功', ['token' => $token, 'expire' => $expire]);
            }
            return jsonFail('登录失败');
        } catch (\Exception $e) {
            return jsonFail($e->getMessage());
        }
    }

    /**商户接单
     * @param array $input 参数
     * @param string $token token
     * @return \think\response\Json
     */
    public static function receiveOrder($input, $token)
    {
        try {
            // 判断商户是否有效
            $store = Store_find($token);
            $storeId = $store['id'];
            if (!$storeId) return jsonFail('获取商户信息失败');
            $storeStatus = Db::table(self::$baseTable)->where('id', $storeId)->value('status');
            if ($storeStatus === null) return jsonFail('该商户不存在');
            // 0 未审核 1已审核 2审核未通过 3已禁用
            if ($storeStatus == 0) return jsonFail('该商户未审核,不能下单');
            if ($storeStatus == 2) return jsonFail('该商户审核未通过,不能下单');
            if ($storeStatus == 3) return jsonFail('该商户已禁用,不能下单');
            // 查询订单状态
            $orderInfo = Db::table(self::$orderTable)->field('status,is_pay')->where('id', $input['id'])->find();
            if ($orderInfo == null) return jsonFail('未知订单');
            if ($orderInfo['status'] !== 0) return jsonFail('该订单不能接单');
//            if ($orderInfo['is_settlement'] == 1) return jsonFail('已结算订单不能接单');
            if ($orderInfo['is_pay'] == 0) return jsonFail('未支付订单不能接单');
            // 修改状态
            $rtn = Db::table(self::$orderTable)
                ->where('id', $input['id'])
                ->where('status', 0)
                ->where('store_id', $storeId)
                ->update(['status' => 1]);
            $order_info = Db::table('eb_order')->where('id',$input['id'])->find();
            $store = Db::table('eb_store')->where('id',$order_info['store_id'])->find();
            $user_list = Db::table('eb_user')->alias('a')
                ->leftJoin('eb_school b', 'a.school_id = b.id')
                ->leftJoin('eb_dormitory c', 'a.dormitory_id = c.id')
                ->field('a.address,a.phone,b.name as school_name,c.name as dormitory_name')
                ->where('a.id',$order_info['user_id'])->find();
            $order_list = Db::table('eb_order_detail')
                ->alias('a')
                ->leftJoin('eb_goods b', 'a.goods_id = b.id')
                ->where('a.order_id', $order_info['id'])
                ->field('a.*,b.*')
                ->select()->toArray();
            $send = new \API_PHP_DEMO();
            $data = combination($store,$user_list,$order_info,$order_list,14,6,3,6);
            $code = $send->printMsg($store['sn'],$data);
            $datas = json_decode($code,true);
            if ($rtn == 1 && $datas['ret']==0) return jsonSuccess('接单成功');
            return jsonFail('接单失败');
        } catch (\Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }
}